import { ActionReducerMapBuilder, AsyncThunk, createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { deleteAddressAPI, fetchAddressListAPI } from '@/API/addressAPI';
import { Address } from '@/type/AddressType';
import { AsyncThunkConfig } from '@reduxjs/toolkit/dist/createAsyncThunk';


type InitialState = {
  addressLit: Address[]
}
const initialState: InitialState = {
  addressLit: [],
};

/**
 * @description 获取收获地址列表的异步函数
 * */
export const fetchAddressList = createAsyncThunk('fetchAddressList', async (_, { rejectWithValue }) => {
  try {
    const { data } = await fetchAddressListAPI();
    return data;
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

/**
 *@description 删除收货地址的接口
 * */

export const deleteAddress: AsyncThunk<'删除收货地址成功', string, AsyncThunkConfig> = createAsyncThunk('deleteAddress', async (addressId, { rejectWithValue }) => {
  try {
    await deleteAddressAPI(addressId);
    return '删除收货地址成功';
  } catch (error: any) {
    return rejectWithValue(error.message);
  }
});

const addressStore = createSlice({
  name: 'addressStore',
  initialState,
  reducers: {},
  extraReducers(builder: ActionReducerMapBuilder<InitialState>) {
    builder.addCase(fetchAddressList.fulfilled, (state: InitialState, action: PayloadAction<Address[]>) => {
      const { payload } = action;
      state.addressLit = payload;
    });
  },

});


export default addressStore.reducer;